package service

import (
	"fmt"
	"io"
	"mime/multipart"
	conf "my-systems/pet-system/configs"
	"os"
	"strconv"
	"time"
)

func UploadAvatarToLocalStatic(uid int, userName string, file multipart.File, myType string) (string, error) {
	newUid := strconv.Itoa(uid)
	basePath := "./pet-system" + conf.AvatarPath + myType + newUid
	if !isDirExist(basePath) {
		CreateDir(basePath)
	}
	nowTime := strconv.FormatInt(time.Now().Unix(), 10)
	avatarPath := basePath + "/" + userName + nowTime + ".jpg"

	// 打开目标文件以写入数据
	out, err := os.Create(avatarPath)
	// 确保文件在函数结束时关闭
	defer out.Close()
	if err != nil {
		return "", err
	}
	// 直接将上传的文件内容复制到目标文件
	_, err = io.Copy(out, file)
	if err != nil {
		return "", err
	}
	fmt.Println("文件保存成功")
	return myType + newUid + "/" + userName + nowTime + ".jpg", nil
}

func CreateDir(path string) {
	err := os.MkdirAll(path, 0755)
	if err != nil {
		fmt.Println("文件夹创建失败")
	}
	fmt.Println("文件夹创建成功")
}

func isDirExist(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}
	return info.IsDir() // 存在且是文件夹返回true
}
